using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
//cubeMesh
[RequireComponent(typeof(MeshFilter ),typeof(MeshRenderer))]
[ExecuteInEditMode]
public class mesh : MonoBehaviour
{
    public Vector3 center = Vector3.zero;
    public float radius = 0.1f;
    public int xSize=8,ySize=5;
    // Start is called before the first frame update
    private Vector3[]vertices;
    private Mesh mymesh;
    private int[]ints;
    private void Awake () 
    {
        StartCoroutine(Generate());
    }
    private IEnumerator Generate () {
        GetComponent<MeshFilter>().mesh=mymesh=new Mesh();
        mymesh.name="Procedural Grid";
		WaitForSeconds wait = new WaitForSeconds(0.05f);
        
		vertices = new Vector3[(xSize + 1) * (ySize + 1)];
        Vector2[] uv = new Vector2[vertices.Length];
        Vector4[]tangents=new Vector4[vertices.Length];
        Vector4 tangent=new Vector4(1f,0f,0f,-1f);
		for (int i = 0, y = 0; y <= ySize; y++) {
			for (int x = 0; x <= xSize; x++, i++) {
				vertices[i] = new Vector3(x, y);
				uv[i] = new Vector2((float)x / xSize, (float)y / ySize);
                tangents[i]=tangent;
			}
		}
        mymesh.vertices=vertices;
        mymesh.uv = uv;
        mymesh.tangents=tangents;
        int []triangles =new int [xSize*6*ySize];
       
        for (int ti = 0, vi = 0, y = 0; y < ySize; y++, vi++) {
			for (int x = 0; x < xSize; x++, ti += 6, vi++) {
				triangles[ti] = vi;
				triangles[ti + 3] = triangles[ti + 2] = vi + 1;
				triangles[ti + 4] = triangles[ti + 1] = vi + xSize + 1;
				triangles[ti + 5] = vi + xSize + 2;
                mymesh.triangles=triangles;
                yield return wait;
			}
            

		}
        mymesh.RecalculateNormals();
        
		
		
        
        

	}

   


    private void OnDrawGizmos() 
    {
       
        
        if (vertices == null)
		{
			return;
		}
		// Gizmos.color = Color.black;
		// for (int i = 0; i < vertices.Length; i++)
		// {
		// 	Gizmos.DrawSphere(vertices[i], 0.1f);
		// }
                
        // Vector3 vec=new Vector3(0.01f,0.02f);
        // Gizmos.DrawSphere(transform.position,0.01f);
        // Gizmos.DrawWireSphere(transform.position,0.01f*1.5f);
        // Gizmos.DrawSphere(transform.position+vec,0.01f);
        // Debug.Log(transform.position);   
                

            
            
            
            
            
        
    }
    
    void Update()
    {  
    }
   


    // Update is called once per frame
}
